package com.ybzl.gateway.config;


import com.alibaba.fastjson.JSONObject;
import com.google.common.collect.Maps;
import lombok.extern.slf4j.Slf4j;
import org.eclipse.paho.client.mqttv3.*;
import org.eclipse.paho.client.mqttv3.persist.MemoryPersistence;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Component;

import javax.annotation.PostConstruct;
import javax.annotation.PreDestroy;
import java.util.Map;
import java.util.UUID;

@Component
@Slf4j
public class EmqxConfig {

    @Value("${serverUri}")
    private String serverUri;

    private static IMqttAsyncClient mqttClient;




    @PostConstruct
    public void init() {
        try {
            MemoryPersistence memoryPersistence = new MemoryPersistence();
            mqttClient = new MqttAsyncClient(serverUri
                    , "iot" + UUID.randomUUID().toString()
                    , memoryPersistence);
            MqttConnectOptions mqttConnectOptions = new MqttConnectOptions();
            mqttConnectOptions.setKeepAliveInterval(20);
            mqttConnectOptions.setAutomaticReconnect(true);
            mqttConnectOptions.setCleanSession(true);
            mqttClient.connect(mqttConnectOptions);
        } catch (MqttException e) {
            e.printStackTrace();
        }
        mqttClient.setCallback(new MqttCallbackExtended() {
            @Override
            public void connectionLost(Throwable throwable) {
                log.error("mqtt错误", throwable);
                try {
                    mqttClient.reconnect();
                } catch (MqttException e) {
                    log.error("重新链接服务器失败", e);
                }
            }

            @Override
            public void messageArrived(String topic, MqttMessage mqttMessage) throws Exception {

            }

            @Override
            public void deliveryComplete(IMqttDeliveryToken token) {

            }

            @Override
            public void connectComplete(boolean reconnect, String serverURI) {

            }

        });

    }

    @PreDestroy
    public void destory() {
        try {
            mqttClient.close();
        } catch (MqttException e) {
            e.printStackTrace();
        }
    }

    public static void push(String topic, boolean isReceive, Object message) {
        MqttMessage sendMessage = new MqttMessage();
        sendMessage.setQos(0);
        Map<String, Object> resultMap = Maps.newHashMap();
        try {
            if (isReceive) {
                sendMessage.setPayload(JSONObject.toJSONString(message).getBytes());
            } else {
                resultMap.put("topic", topic);
                resultMap.put("data", message);
                sendMessage.setPayload(JSONObject.toJSONString(resultMap).getBytes());
            }
            mqttClient.publish(topic, sendMessage);
        } catch (MqttException e) {
            e.printStackTrace();
        }
    }

}

